package com.sheeran.aichat.exception;

import com.sheeran.aichat.utils.rest.ResponseCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.Optional;

/**
 * @author: sheeran
 * @create: 2025/02/10
 */
@Data
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class BusinessException extends RuntimeException {
    private static final long serialVersionUID = 7013604354853017252L;

    /**
     * 错误码
     */
    private int code;

    /**
     * 错误信息
     */
    private String msg;

    public BusinessException(ResponseCode responseCode) {
        super(responseCode.getMsg());
        this.code = responseCode.getCode();
        this.msg = responseCode.getMsg();
    }

    public BusinessException(ResponseCode responseCode, String message) {
        super(message);
        this.code = responseCode.getCode();
        this.msg = responseCode.getMsg();
    }

    public BusinessException(int code, String msg, String message) {
        super(message);
        this.code = code;
        this.msg = msg;
    }

    public static BusinessException buildFromFeignCause(Throwable cause) {
        BusinessException businessEx = null;
        if (cause instanceof BusinessException) {
            businessEx = (BusinessException) cause;
        }
        if (cause != null && cause.getCause() instanceof BusinessException) {
            businessEx = (BusinessException) cause.getCause();
        }

        return Optional.ofNullable(businessEx).orElse(new BusinessException(ResponseCode.REMOTE_CALL_ERROR, "远程调用失败"));
    }
}
